<?php
/**
 * Created by PhpStorm.
 * User: muhe0
 * Date: 2017/11/30
 * Time: 11:24
 */

namespace Lin\Dnah\Providers;


use Carbon\Carbon;
use Illuminate\Cache\RedisStore;
use Illuminate\Cache\Repository;
use Illuminate\Support\Facades\Cache;
use Lin\Dnah\Model\DnahModel;
use Lin\Dnah\TimeReporInterface;

class UrlTotalHandler implements TimeReporInterface
{
    function shut($timereport)
    {
        $url = $this->filter_url();
        if(!$url){return false ; }

        //记录
        $this->record($url,$timereport);
    }
    const TIMES="TIMES";
    //微妙
    const MILSECT="MILIl";


    private function record($uri,$timemeta){
        //记录到缓存中
        $cache=Cache::store(config('dnah.cache'));
        $cache= $cache->tags('dnah.uri.'.md5($uri));//分组
        // Repository::class
        $maxtimes =  config('dnah.max_times');
        $time_key =$this->key($uri,self::TIMES);
        if($_lastt=$cache->get($time_key) ){
            if($_lastt >= $maxtimes ){
                //写DB //满N次
                $m= new DnahModel();
                $tims= $cache->get($this->key($uri,self::TIMES));
                $mils= $cache->get($this->key($uri,self::MILSECT));
                //
                $m->uri = $uri ;
                $m->uri_hash = md5($m->uri) ;

                $mang=app(DnahServiceProvider::SINGNAME);
                $m->utime =  $mang->getCollector()->getDefaultDataFormatter()->formatDuration($mils / $tims);
                $m->lastzeit= Carbon::createFromTimestamp($timemeta['start'] ) ;//
                $m->updateOrCreate(['uri_hash'=>$m->uri_hash],$m->getAttributes());
                //clear now
                $this->clearCache($cache,$uri);
            }
        }


        //$cche  RedisStore->connection() predisClient
        $this->saveCache($cache,$uri,1,$timemeta['end']-$timemeta['start']);

    }



    /**
     *
     * @param $cache 缓存类
     * @param $uri PATH地址
     * @param $times 累计的次数
     * @param $mids  累计的时间
     */
    protected function saveCache($cache,$uri,$times,$milsec){
        $time_key =$this->key($uri,self::TIMES);
        //$mds='dnah.uri.'.md5($uri);
        $cache
            //->tags($mds)
            ->increment($time_key,$times);
        $mil_key=$this->key($uri,self::MILSECT);
        //.$cache->tags($mds)->get($mil_key);$milsec
        $milv=$cache->get($mil_key);
        if($milv){
            //毫秒累计
            $milsec+=$milv;
        }
        $cache->put($mil_key,$milsec,372000 );

    }

    /**
     * 清除一个URI
     * @param $cache
     * @param $uri
     */
    protected  function clearCache($cache,$uri){
        $mds='dnah.uri.'.md5($uri);
        $cache->flush();
        //$cache->pull($mds.self::TIMES);
    }
    private function key($uri,$k){
        // return md5($uri). 因为已经有分组 这个没必要了
        return $k;
    }
    /*
     * 返回要记录的URI的PATH
     */
    public function filter_url(){
        $req= app('request') ;
        $reurk=$req->getPathInfo();
        //filter
        $filtliste=   config('dnah.exclude');
        $ok=true ;
        foreach ($filtliste as $filtlisteline){

            $x= preg_filter('#'.$filtlisteline.'#',"$0",$reurk);
            if($x!=null){
                $ok=false ;break;
            }
        }
        if($ok){
            return $reurk ;
        }
        return false ;
        //return
    }
}